package com.bf.xpdd.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.bf.xpdd.config.ConfigParameter;
import com.bf.xpdd.domain.ActivityBean;
import com.bf.xpdd.domain.ActivityItemBean;
import com.bf.xpdd.domain.ActivitySettingBean;
import com.bf.xpdd.domain.SiteBuyer;
import com.bf.xpdd.domain.SiteDiscount;
import com.bf.xpdd.domain.SiteItem;
import com.bf.xpdd.domain.SiteSeller;
import com.bf.xpdd.domain.SiteShop;
import com.bf.xpdd.domain.TaobaoItemResult;
import com.bf.xpdd.exception.BaseException;
import com.bf.xpdd.service.ActivityItemService;
import com.bf.xpdd.service.ActivityService;
import com.bf.xpdd.service.ActivitySettingService;
import com.bf.xpdd.service.TaobaoService;
import com.bf.xpdd.util.JSONTranslator;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.Promotion;
import com.taobao.api.domain.UserTag;
import com.taobao.api.request.FavoriteAddRequest;
import com.taobao.api.request.ItemsListGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.request.MarketingPromotionAddRequest;
import com.taobao.api.request.MarketingPromotionDeleteRequest;
import com.taobao.api.request.MarketingPromotionsGetRequest;
import com.taobao.api.request.MarketingTagAddRequest;
import com.taobao.api.request.MarketingTagDeleteRequest;
import com.taobao.api.request.MarketingTagsGetRequest;
import com.taobao.api.request.MarketingTaguserAddRequest;
import com.taobao.api.request.MarketingTaguserDeleteRequest;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.response.FavoriteAddResponse;
import com.taobao.api.response.ItemsListGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.MarketingPromotionAddResponse;
import com.taobao.api.response.MarketingPromotionDeleteResponse;
import com.taobao.api.response.MarketingPromotionsGetResponse;
import com.taobao.api.response.MarketingTagAddResponse;
import com.taobao.api.response.MarketingTagDeleteResponse;
import com.taobao.api.response.MarketingTagsGetResponse;
import com.taobao.api.response.MarketingTaguserAddResponse;
import com.taobao.api.response.MarketingTaguserDeleteResponse;
import com.taobao.api.response.UserGetResponse;

/**
 * TBServiceImpl
 * 
 * @author Fantastic
 * @version 1.0.0 2011-06-01
 * @since 1.0.0
 */
@Component
public class TaobaoServiceImpl implements TaobaoService
{
	/** logger */
	private static final Logger log = Logger.getLogger(TaobaoServiceImpl.class);
	
	/**
	 * get items by
	 * @throws ParseException 
	 * @throws ApiException 
	 */
	public List<Item> getItemBySession(String sessionKey) throws BaseException
	{
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
		req.setFields("num_iid, title, pic_url, price");
		//req.setQ("N97");
		//req.setCid(1512L);
		//req.setSellerCids("11");
		req.setPageNo(1L);
		//req.setHasDiscount(true);
		//req.setHasShowcase(true);
		req.setOrderBy("list_time:desc");
		req.setIsTaobao(true);
		//req.setIsEx(true);
		req.setPageSize(3L);
		
		ItemsOnsaleGetResponse response = null;
		try {
			Date startDatetime = SimpleDateFormat.getDateTimeInstance().parse("2000-01-01 00:00:00");
//			req.setStartModified(startDatetime);
			Date endDatetime = SimpleDateFormat.getDateTimeInstance().parse("2000-01-01 00:00:00");
//			req.setEndModified(endDatetime);
			response = client.execute(req , sessionKey);
			
		} catch (ParseException e)
		{
			log.error("ParseException", e);
			throw new BaseException("商品查询时间转换异常");
		} catch (ApiException e)
		{
			log.error("ApiException", e);
			throw new BaseException("商品查询淘宝接口调用异常");
		}
		
		if(null != response)
		{
			return response.getItems();
		}
		return null;
	}
	
	/**
	 * get items by
	 * @throws ParseException 
	 * @throws ApiException 
	 */
	public TaobaoItemResult getItemByParameter(String sessionKey, String queryKey, long pageNo, long pageSize) throws BaseException
	{
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
		req.setFields("num_iid, title, pic_url, price");
		//req.setQ("N97");
		//req.setCid(1512L);
		//req.setSellerCids("11");
		req.setPageNo(pageNo);
		//req.setHasDiscount(true);
		//req.setHasShowcase(true);
		req.setOrderBy("list_time:desc");
		req.setIsTaobao(true);
		//req.setIsEx(true);
		req.setPageSize(pageSize);
		
		ItemsOnsaleGetResponse response = null;
		try {
			Date startDatetime = SimpleDateFormat.getDateTimeInstance().parse("2000-01-01 00:00:00");
//			req.setStartModified(startDatetime);
			Date endDatetime = SimpleDateFormat.getDateTimeInstance().parse("2000-01-01 00:00:00");
//			req.setEndModified(endDatetime);
			response = client.execute(req , sessionKey);
			
		} 
		catch (ParseException e)
		{
			log.error("ParseException", e);
			throw new BaseException("商品查询时间转换异常");
		} 
		catch (ApiException e)
		{
			log.error("ApiException", e);
			throw new BaseException("商品查询淘宝接口调用异常");
		}
		
		if(null != response)
		{
			TaobaoItemResult result = new TaobaoItemResult();
			result.setTotal(response.getTotalResults());
			result.setItemList(response.getItems());
			return result;
		}
		return null;
	}
	
	/**
	 * 
	 */
	public List changeSiteItem(List<Item> itemList) throws BaseException {
		List<SiteItem> newItemList = new ArrayList<SiteItem>();
		SiteItem newItem;
		for(Item tempItem : itemList)
		{
			newItem = new SiteItem();
			newItem.setCode(tempItem.getNumIid());
			newItem.setName(tempItem.getTitle());
			newItem.setPicUrl("<img src='" + tempItem.getPicUrl() + "' height='20' width='20' />");
			newItem.setStatus("未使用");
			newItem.setPrice(tempItem.getPrice());
			newItemList.add(newItem);
		}
		return newItemList;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public List<SiteItem> findItemById(String id) throws BaseException 
	{
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.FRONT_APPKEY, ConfigParameter.FRONT_APP_SECRET);
		ItemsListGetRequest req=new ItemsListGetRequest();
		req.setFields("num_iid,title,nick,price,detail_url,pic_url");
		req.setNumIids(id);
		List<SiteItem> resultList = new ArrayList<SiteItem>(0); 
		SiteItem tempItem = null;
		
		try 
		{
			ItemsListGetResponse response = client.execute(req);
			List<Item> itemList = response.getItems();
			
			if(null != itemList && !itemList.isEmpty())
			{
				for(Item item : itemList)
				{
					tempItem = new SiteItem();
					tempItem.setCode(item.getNumIid());
					tempItem.setName(item.getTitle());
					tempItem.setPicUrl(item.getPicUrl());
					tempItem.setPrice(item.getPrice());
					tempItem.setDetailUrl(item.getDetailUrl());
					resultList.add(tempItem);
				}
			}
		}
		catch (ApiException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return resultList;
	}

	/**
	 * {@inheritDoc}
	 * @return 
	 */
	@Override
	public List<Promotion> addDiscount(String sessionKey, ActivityBean activity, List<Long> items, ActivitySettingBean setting, long tagId) 
	{
		StringBuilder idStr = new StringBuilder();
		for(Long id : items)
		{
			idStr.append(id).append(",");
		}
		String ids = idStr.substring(0, idStr.length() - 1);
		
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		MarketingPromotionAddRequest req = new MarketingPromotionAddRequest();
		req.setNumIids(ids);
		req.setDiscountType("DISCOUNT");
		req.setDiscountValue(setting.getBaseLine() + "");
		req.setStartDate(activity.getBeginTime());
		req.setEndDate(activity.getEndTime());
		req.setPromotionTitle("血拼价");
		req.setTagId(tagId);
		req.setPromotionDesc("血拼到底优惠价格");
		try 
		{
			MarketingPromotionAddResponse response = client.execute(req, sessionKey);
			return response.getPromotions();
		} 
		catch (ApiException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public UserTag addTag(String sessionKey, String tagName, String desc) throws BaseException
	{
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		MarketingTagAddRequest req = new MarketingTagAddRequest();
		req.setTagName(tagName);
		req.setDescription(desc);
		try 
		{
			MarketingTagAddResponse response = client.execute(req, sessionKey);
			return response.getUserTag();
		}
		catch (ApiException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new BaseException("添加人群标签" + tagName + "异常");
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean removeTag(String sessionKey, long tagId) throws BaseException 
	{
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		MarketingTagDeleteRequest req = new MarketingTagDeleteRequest();
		req.setTagId(tagId);
		MarketingTagDeleteResponse response;
		try 
		{
			response = client.execute(req , sessionKey);
			return response.isSuccess();
		} 
		catch (ApiException e)
		{
			throw new BaseException("删除人群标签失败");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean addTagBuyer(String sessionKey, long tagId, String nick) throws BaseException
	{
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		MarketingTaguserAddRequest req = new MarketingTaguserAddRequest();
		req.setTagId(tagId);
		req.setNick(nick);
		MarketingTaguserAddResponse response;
		try 
		{
			response = client.execute(req, sessionKey);
			return response.isSuccess();
		}
		catch (ApiException e) 
		{
			throw new BaseException("添加用户折扣信息失败。");
		}
	}

	/**
	 * {@inheritDoc}
	 * @throws BaseException 
	 */
	@Override
	public boolean removeDiscount(String sessionKey, long discountId) throws BaseException 
	{
		TaobaoClient client=new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		MarketingPromotionDeleteRequest req = new MarketingPromotionDeleteRequest();
		req.setPromotionId(discountId);
		try
		{
			MarketingPromotionDeleteResponse response = client.execute(req , sessionKey);
			return response.getIsSuccess();
		}
		catch (ApiException e) 
		{
			throw new BaseException("删除折扣信息失败。");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String findPromotionByItemId(String sessionKey, long itemId) throws BaseException 
	{
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		MarketingPromotionsGetRequest req = new MarketingPromotionsGetRequest();
		req.setStatus("ACTIVE");
		req.setFields("promotion_id, promotion_title, item_id, discount_value, tag_id, item_detail_url");
		req.setNumIid(itemId + "");
		MarketingPromotionsGetResponse response;
		try
		{
			response = client.execute(req, sessionKey);
			return response.getBody();
		} 
		catch (ApiException e) 
		{
			throw new BaseException("查询商品折扣信息失败。");
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void findUserByNick(SiteSeller seller) throws BaseException 
	{
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		UserGetRequest req = new UserGetRequest();
		req.setNick(seller.getNick());
		req.setFields("status");
		try 
		{
			UserGetResponse response = client.execute(req, seller.getTopSession());
			if("27".equals(response.getErrorCode()))
			{
				throw new BaseException("27", "淘宝请求超出限制");
			}
			else if(null != response.getErrorCode())
			{
				throw new BaseException("-1", "用户session失效");
			}
		} 
		catch (ApiException e) 
		{
			throw new BaseException("-2", "请求淘宝数据失败");
		}

	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void removeTagUser(String topSession, long tagId, String nick) throws BaseException 
	{
		TaobaoClient client=new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		MarketingTaguserDeleteRequest req = new MarketingTaguserDeleteRequest();
		req.setTagId(tagId);
		req.setNick(nick);
		MarketingTaguserDeleteResponse response;
		try 
		{
			response = client.execute(req, topSession);
		} 
		catch (ApiException e) 
		{
			throw new BaseException("删除" + nick + "优惠用户" + tagId + "失败");
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public String addPromotionFromAction(ActivitySettingService activitySettingService, SiteSeller seller, ActivityBean bean, ArrayList<Long> idList) throws BaseException
	{
		//获取tagid
		List<UserTag> tagList = this.findTagBySessionKey(seller.getTopSession());
		
		try 
		{
			if(null != tagList && !tagList.isEmpty())
			{
				for(UserTag tag : tagList)
				{
					this.removeTag(seller.getTopSession(), tag.getTagId());
				}
			}
			
			tagList = new ArrayList<UserTag>(0);
			StringBuilder builder = new StringBuilder();
			for(int i = 0; i < 10; i++)
			{
				UserTag tag = this.addTag(seller.getTopSession(), seller.getNick() + "的标签" + i, seller.getNick() + "的标签描述" + i);
				if(null == tag)
				{
					continue;
				}
				tagList.add(tag);
				builder.append(tag.getTagId()).append(",");
			}
			//String tagStr = builder.substring(0, -1);
		}
		catch (BaseException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//向淘宝数据库中添加折扣信息
		long tagId;
		List<SiteDiscount> disList = new ArrayList<SiteDiscount>();
		SiteDiscount discount = null;
		try
		{
			ActivitySettingBean setting = activitySettingService.queryActSettingById(bean.getModleId());
			double baseLine = setting.getBaseLine();
			for(int i = 0; i < 10; i++)
			{
				tagId = tagList.get(i).getTagId();
				discount = new SiteDiscount();
				discount.setTagId(tagId);
				setting.setBaseLine(baseLine / 10 + (10 - baseLine / 10) / 10 * i);
				List<Promotion> proList = this.addDiscount(seller.getTopSession(), bean, idList, setting, tagId);
				for(Promotion pro : proList)
				{
					discount.getPromotionIdList().add(pro.getPromotionId());
				}
				disList.add(discount);
			}
			return JSONTranslator.toJSON(disList);
		}
		catch (Exception e) 
		{
			throw new BaseException("添加人群标签用户失败");
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	public List<UserTag> findTagBySessionKey(String sessionKey) throws BaseException
	{
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.BACK_APPKEY, ConfigParameter.BACK_APP_SECRET);
		MarketingTagsGetRequest req = new MarketingTagsGetRequest();
		req.setFields("tag_id,tag_name");
		try 
		{
			MarketingTagsGetResponse response = client.execute(req , sessionKey);
			return response.getUserTags();
		} 
		catch (ApiException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new BaseException("查询人群标签异常");
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void removePromotionByAction(ActivityService activityService, SiteSeller seller, long aid)
			throws BaseException
	{
		//获取活动信息
		ActivityBean activity = activityService.queryActivityBeanById(aid);
		//获取活动对应的标签、定向优惠信息
		List<LinkedHashMap> discountList = JSONTranslator.toBean(activity.getTagId(), ArrayList.class);
		int len = discountList.size();
		for(int i = 0; i < len; i++)
		{
			LinkedHashMap map = discountList.get(i);
			List<Integer> promotionList = (List<Integer>) map.get("promotionIdList");
			//删除定向优惠
			for(int promotionId : promotionList)
			{
				this.removeDiscount(seller.getTopSession(), promotionId);
			}
			//删除标签
			this.removeTag(seller.getTopSession(), Long.parseLong(map.get("tagId").toString()));
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void findUserIsExistByNick(String nick) throws BaseException 
	{
		TaobaoClient client = new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.FRONT_APPKEY, ConfigParameter.FRONT_APP_SECRET);
		UserGetRequest req = new UserGetRequest();
		req.setFields("status");
		req.setNick(nick);
		try 
		{
			UserGetResponse response = client.execute(req);
			if(null != response.getErrorCode())
			{
				throw new BaseException("-1", response.getSubMsg());
			}
		} 
		catch (ApiException e) 
		{
			throw new BaseException("-2", "请求淘宝数据失败");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void addFavorite(SiteShop shop, SiteBuyer buyer) throws BaseException
	{
		try 
		{
			TaobaoClient client=new DefaultTaobaoClient(ConfigParameter.ACCESS_URL, ConfigParameter.FRONT_APPKEY, ConfigParameter.FRONT_APP_SECRET);
			FavoriteAddRequest req = new FavoriteAddRequest();
			req.setItemNumid(shop.getIdShop());
			req.setCollectType("SHOP");
			req.setShared(false);
			FavoriteAddResponse response = client.execute(req , buyer.getTopSession());
			if(!response.getSuccess())
			{
				throw new BaseException("添加收藏失败");
			}
		} 
		catch (ApiException e) 
		{
			throw new BaseException("添加收藏失败");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void addPromotionFromAction(ActivityService activityService, ActivityItemService itemService, ActivitySettingService activitySettingService, SiteSeller seller) throws BaseException 
	{
		List<ActivityBean> actionList = activityService.queryActivityInfoByNick(seller.getNick());
		List<SiteDiscount> disList = new ArrayList<SiteDiscount>();
		
		if(null == actionList || actionList.isEmpty())
		{
			throw new BaseException("没有任何宝贝组");
		}
		
		List<Long> idList = null;
		
		for(ActivityBean bean : actionList)
		{
		
			//获取tagid
			List<UserTag> tagList = this.findTagBySessionKey(seller.getTopSession());
			
			//如果tagid为空或不足10个 添加
			if(null == tagList || tagList.size() < 10)
			{
				throw new BaseException("人群标签不正确，请联系管理员。");
			}
			
			//向淘宝数据库中添加折扣信息
			long tagId;
			
			SiteDiscount discount = null;
			try
			{
				ActivitySettingBean setting = activitySettingService.queryActSettingById(bean.getModleId());
				double baseLine = setting.getBaseLine();
				
				//根据活动id获取宝贝信息
				List<ActivityItemBean> itemList = itemService.queryActivityItemByActId(bean.getAid());
				
				//没有宝贝则继续下一个活动
				if(null == itemList || itemList.isEmpty())
				{
					continue;
				}
				
				idList = new ArrayList<Long>(0);
				
				//转化为id列表
				for(ActivityItemBean tempItem : itemList)
				{
					idList.add(tempItem.getItemId());
				}
				
				//添加折扣
				for(int i = 0; i < 10; i++)
				{
					tagId = tagList.get(i).getTagId();
					discount = new SiteDiscount();
					discount.setTagId(tagId);
					setting.setBaseLine(baseLine / 10 + (10 - baseLine / 10) / 10 * i);
					
					List<Promotion> proList = this.addDiscount(seller.getTopSession(), bean, idList, setting, tagId);
					for(Promotion pro : proList)
					{
						discount.getPromotionIdList().add(pro.getPromotionId());
					}
					disList.add(discount);
				}
				
				//更新折扣信息
				activityService.saveActivityDiscount(bean, JSONTranslator.toJSON(disList));
			}
			catch (Exception e) 
			{
				throw new BaseException("添加人群标签用户失败");
			}
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void removePromotionByAction(ActivityService activityService, SiteSeller seller) throws BaseException 
	{
		//获取活动信息
		List<ActivityBean> actionList = activityService.queryActivityInfoByNick(seller.getNick());
		
		if(null == actionList || actionList.isEmpty())
		{
			throw new BaseException("没有任何宝贝组");
		}
		
		for(ActivityBean activity : actionList)
		{
			//获取活动对应的标签、定向优惠信息
			List<LinkedHashMap> discountList = JSONTranslator.toBean(activity.getTagId(), ArrayList.class);
			int len = discountList.size();
			for(int i = 0; i < len; i++)
			{
				LinkedHashMap map = discountList.get(i);
				List<Integer> promotionList = (List<Integer>) map.get("promotionIdList");
				//删除定向优惠
				for(int promotionId : promotionList)
				{
					this.removeDiscount(seller.getTopSession(), promotionId);
				}
				//删除标签
				this.removeTag(seller.getTopSession(), Long.parseLong(map.get("tagId").toString()));
			}
		}
	}
	
}
